import pyaudio
import numpy as np

CHUNK = 1024  # 每次读取的音频数据块大小
FORMAT = pyaudio.paInt16  # 音频格式
CHANNELS = 1  # 声道数
RATE = 44100  # 采样率（每秒采样次数）

audio = pyaudio.PyAudio()

# 打开音频流
stream = audio.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

print("Recording...")

try:
    while True:
        # 读取音频数据
        data = stream.read(CHUNK)
        # 将二进制数据转换为numpy数组
        audio_data = np.frombuffer(data, dtype=np.int16)
        # 在这里你可以对音频数据进行处理，比如分析、保存等操作
        # 这里只是简单地输出音频数据的均值
        print(np.mean(audio_data))
except KeyboardInterrupt:
    print("Recording stopped.")

# 关闭音频流
stream.stop_stream()
stream.close()
audio.terminate()
